package com.dynamo.transport.network.practise.channel.socket.nio;

import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author duanyimiao
 * @create 2018-12-17 11:50 AM
 * @description
 **/
public class NioWorkerPool {

    private Executor executor;
    private int workerCount;
    private Worker[] workers;
    private AtomicInteger counter = new AtomicInteger();

    //TODO 对初始化的参数进行校验
    public NioWorkerPool(Executor executor, int workerCount) {
        this.executor = executor;
        this.workerCount = workerCount;
        workers = new Worker[workerCount];
        initWorkers(executor, workerCount);
    }

    private void initWorkers(Executor executor, int workerCount) {

        for (int i = 0; i < workerCount; i++){
            workers[i] = new NioWorker();
            executor.execute((NioWorker)workers[i]);
        }
    }

    public Worker nextWorker(){
        return workers[counter.getAndIncrement()%workerCount];
    }

}
